package com.becca.cake.core.spring.interceptor.impl;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.becca.cake.util.PMSConstants;

/**
 * 拦截器,用于控制是否登录
 * @author hejinguo
 * @version $Id: HandlerDispatcherContextInterceptor.java, v 0.1 2013-9-14 上午12:01:08
 */
public class HandlerDispatcherContextInterceptor extends HandlerInterceptorAdapter {
    private final static Log logger = LogFactory.getLog(HandlerDispatcherContextInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) {
        if (request.getSession().getAttribute(PMSConstants.LOGIN_USER) == null) {
            logger.info("拦截请求URL:" + request.getRequestURL());
            logger.info("非法请求,请先登录!");
            try {
                response.sendRedirect(request.getContextPath() + "/login.jsp");
            } catch (IOException e) {
                logger.error("拦截非法请求!IO异常", e);
            }
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
    }

    @Override
    public void postHandle(HttpServletRequest httpservletrequest,
                           HttpServletResponse httpservletresponse, Object obj,
                           ModelAndView modelandview) throws Exception {

    }

}
